﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Rodunu.Movies.Interfaces.Data;

namespace Rodunu.Movies.Data
{
    public class UserMoviesRepository : IUserMoviesRepository
    {
        private static ISession _Session;

        #region IUserMoviesRepository Members

        public void Create(Contracts.UserMovies identifiable)
        {
            _Session = DBHelper.GetCurrentSession();
            ITransaction transaction = _Session.BeginTransaction();
            _Session.Save(identifiable);
            transaction.Commit();
            DBHelper.CloseSession();
        }

        public Contracts.UserMovies Find(long userId, long movieId)
        {
            _Session = DBHelper.GetCurrentSession();
            return (Contracts.UserMovies)DBHelper.GetCurrentSession().CreateCriteria(typeof(Contracts.UserMovies))
                .Add(Restrictions.Eq("UserId", userId))
                .Add(Restrictions.Eq("MovieId", movieId))
                .UniqueResult();
        }

        public IList<Contracts.UserMovies> FindAll()
        {
            return DBHelper.GetCurrentSession().CreateCriteria(typeof(Contracts.UserMovies)).List<Contracts.UserMovies>();
        }

        public void Delete(Contracts.UserMovies identifiable)
        {
            _Session = DBHelper.GetCurrentSession();
            ITransaction transaction = _Session.BeginTransaction();
            _Session.Delete(identifiable);
            transaction.Commit();
            DBHelper.CloseSession();
        }

        public void Update(Contracts.UserMovies identifiable)
        {
            _Session = DBHelper.GetCurrentSession();
            ITransaction transaction = _Session.BeginTransaction();
            _Session.Update(identifiable);
            transaction.Commit();
            DBHelper.CloseSession();
        }

        #endregion
    }
}
